<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>测试二：沪深大盘实时数据</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }

        .header {
            text-align: center;
            margin-bottom: 2rem;
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 0.5rem;
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .controls {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
            display: flex;
            gap: 1rem;
            align-items: center;
            flex-wrap: wrap;
        }

        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-2px);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #1e7e34;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .status {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 600;
        }

        .status-dot {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background: #dc3545;
        }

        .status-dot.running {
            background: #28a745;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .market-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .market-card {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            transition: transform 0.3s ease;
        }

        .market-card:hover {
            transform: translateY(-4px);
        }

        .market-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .market-code {
            font-size: 0.9rem;
            color: #666;
        }

        .market-name {
            font-size: 1.2rem;
            font-weight: bold;
            color: #333;
        }

        .market-price {
            font-size: 2rem;
            font-weight: bold;
            margin: 0.5rem 0;
        }

        .market-change {
            font-size: 1rem;
            font-weight: 600;
        }

        .price-up {
            color: #dc3545;
        }

        .price-down {
            color: #28a745;
        }

        .market-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.5rem;
            margin-top: 1rem;
            font-size: 0.9rem;
            color: #666;
        }

        .chart-container {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }

        .chart-title {
            font-size: 1.3rem;
            font-weight: bold;
            margin-bottom: 1rem;
            color: #333;
        }

        .loading {
            text-align: center;
            padding: 2rem;
            color: #666;
        }

        .error {
            background: #f8d7da;
            color: #721c24;
            padding: 1rem;
            border-radius: 8px;
            margin: 1rem 0;
        }

        .success {
            background: #d4edda;
            color: #155724;
            padding: 1rem;
            border-radius: 8px;
            margin: 1rem 0;
        }

        .last-update {
            text-align: center;
            color: #666;
            font-size: 0.9rem;
            margin-top: 1rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 测试二：沪深大盘实时数据</h1>
            <p>从网上获取沪深大盘实时价格数据，每隔3秒获取一次，保存到Redis，前端通过Redis获取数据并图表展示</p>
        </div>

        <div class="controls">
            <button id="toggleBtn" class="btn btn-success" onclick="toggleCollection()">
                <span id="toggleIcon">🚀</span>
                <span id="toggleText">启动数据采集</span>
            </button>
            <button class="btn btn-primary" onclick="refreshData()">🔄 刷新数据</button>
            <button class="btn btn-primary" onclick="testRedis()">🔧 测试Redis</button>
            <a href="/dashboard" class="btn btn-primary">🏠 返回仪表板</a>
            
            <div class="status">
                <div class="status-dot" id="statusDot"></div>
                <span id="statusText">未启动</span>
            </div>
        </div>

        <div id="messageArea"></div>

        <div class="market-grid" id="marketGrid">
            <div class="loading">正在加载大盘数据...</div>
        </div>

        <div class="chart-container">
            <div class="chart-title">📈 大盘指数实时走势图</div>
            <div id="marketChart" style="height: 500px;"></div>
        </div>

        <div class="last-update" id="lastUpdate"></div>
    </div>

    <script>
        let updateInterval = null;
        let chartData = {};

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkStatus();
            refreshData();
            startAutoRefresh();
        });

        // 检查服务状态
        async function checkStatus() {
            try {
                const response = await fetch('/api/market/status');
                const result = await response.json();
                
                if (result.success) {
                    const status = result.data;
                    updateStatusDisplay(status.running, status.redis_connected);
                }
            } catch (error) {
                console.error('检查状态失败:', error);
            }
        }

        // 更新状态显示
        function updateStatusDisplay(running, redisConnected) {
            const statusDot = document.getElementById('statusDot');
            const statusText = document.getElementById('statusText');

            if (running) {
                statusDot.classList.add('running');
                statusText.textContent = `运行中 (Redis: ${redisConnected ? '已连接' : '未连接'})`;
            } else {
                statusDot.classList.remove('running');
                statusText.textContent = '未启动';
            }

            // 同步更新切换按钮状态
            updateToggleButton(running);
        }

        // 智能切换数据采集状态
        async function toggleCollection() {
            const toggleBtn = document.getElementById('toggleBtn');
            const toggleIcon = document.getElementById('toggleIcon');
            const toggleText = document.getElementById('toggleText');

            // 检查当前状态
            const isRunning = toggleBtn.classList.contains('btn-danger');

            try {
                if (isRunning) {
                    // 当前运行中，执行停止操作
                    showMessage('正在停止数据采集...', 'info');
                    const response = await fetch('/api/market/stop', { method: 'POST' });
                    const result = await response.json();

                    if (result.success) {
                        showMessage('⏹️ 数据采集已停止', 'success');
                        updateToggleButton(false);
                        stopAutoRefresh();
                    } else {
                        showMessage('❌ 停止失败: ' + result.message, 'error');
                    }
                } else {
                    // 当前未运行，执行启动操作
                    showMessage('正在启动数据采集...', 'info');
                    const response = await fetch('/api/market/start', { method: 'POST' });
                    const result = await response.json();

                    if (result.success) {
                        showMessage('✅ 数据采集已启动', 'success');
                        updateToggleButton(true);
                        startAutoRefresh();
                    } else {
                        showMessage('❌ 启动失败: ' + result.message, 'error');
                    }
                }

                // 更新状态显示
                setTimeout(checkStatus, 1000);

            } catch (error) {
                showMessage('❌ 操作失败: ' + error.message, 'error');
            }
        }

        // 更新切换按钮的外观
        function updateToggleButton(isRunning) {
            const toggleBtn = document.getElementById('toggleBtn');
            const toggleIcon = document.getElementById('toggleIcon');
            const toggleText = document.getElementById('toggleText');

            if (isRunning) {
                // 运行状态：显示停止按钮
                toggleBtn.className = 'btn btn-danger';
                toggleIcon.textContent = '⏹️';
                toggleText.textContent = '停止采集';
            } else {
                // 停止状态：显示启动按钮
                toggleBtn.className = 'btn btn-success';
                toggleIcon.textContent = '🚀';
                toggleText.textContent = '启动数据采集';
            }
        }

        // 刷新数据
        async function refreshData() {
            try {
                await loadMarketData();
                await loadChartData();
                document.getElementById('lastUpdate').textContent = 
                    `最后更新: ${new Date().toLocaleString()}`;
            } catch (error) {
                console.error('刷新数据失败:', error);
            }
        }

        // 加载大盘数据
        async function loadMarketData() {
            try {
                const response = await fetch('/api/market/indices');
                const result = await response.json();
                
                if (result.success) {
                    displayMarketData(result.data);
                } else {
                    showMessage('获取大盘数据失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('获取大盘数据失败: ' + error.message, 'error');
            }
        }

        // 显示大盘数据
        function displayMarketData(data) {
            const grid = document.getElementById('marketGrid');
            
            if (!data || Object.keys(data).length === 0) {
                grid.innerHTML = '<div class="loading">暂无大盘数据</div>';
                return;
            }

            let html = '';
            for (const [code, indexData] of Object.entries(data)) {
                const changeClass = parseFloat(indexData.change_percent) >= 0 ? 'price-up' : 'price-down';
                const changeSymbol = parseFloat(indexData.change_percent) >= 0 ? '+' : '';
                
                html += `
                    <div class="market-card">
                        <div class="market-header">
                            <div>
                                <div class="market-code">${code}</div>
                                <div class="market-name">${indexData.name}</div>
                            </div>
                        </div>
                        <div class="market-price ${changeClass}">${indexData.current}</div>
                        <div class="market-change ${changeClass}">
                            ${changeSymbol}${indexData.change_amount} (${changeSymbol}${indexData.change_percent}%)
                        </div>
                        <div class="market-details">
                            <div>开盘: ${indexData.open}</div>
                            <div>最高: ${indexData.high}</div>
                            <div>最低: ${indexData.low}</div>
                            <div>成交量: ${(indexData.volume / 100000000).toFixed(1)}亿</div>
                        </div>
                    </div>
                `;
            }
            
            grid.innerHTML = html;
        }

        // 加载图表数据
        async function loadChartData() {
            try {
                const response = await fetch('/api/market/history?days=1');
                const result = await response.json();
                
                if (result.success && result.data.length > 0) {
                    updateChart(result.data);
                }
            } catch (error) {
                console.error('加载图表数据失败:', error);
            }
        }

        // 更新图表
        function updateChart(historyData) {
            const traces = [];
            const indices = ['sh000001', 'sz399001', 'sz399006', 'sh000300', 'sz399905'];
            const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7'];
            
            indices.forEach((code, index) => {
                const data = historyData
                    .filter(record => record.data && record.data[code])
                    .map(record => ({
                        x: new Date(record.timestamp),
                        y: parseFloat(record.data[code].current)
                    }));
                
                if (data.length > 0) {
                    traces.push({
                        x: data.map(d => d.x),
                        y: data.map(d => d.y),
                        type: 'scatter',
                        mode: 'lines+markers',
                        name: getIndexName(code),
                        line: { color: colors[index], width: 2 },
                        marker: { size: 4 }
                    });
                }
            });

            const layout = {
                title: '沪深大盘实时走势',
                xaxis: { title: '时间' },
                yaxis: { title: '指数点位' },
                showlegend: true,
                margin: { t: 50, r: 50, b: 50, l: 80 }
            };

            Plotly.newPlot('marketChart', traces, layout, {responsive: true});
        }

        // 获取指数名称
        function getIndexName(code) {
            const names = {
                'sh000001': '上证指数',
                'sz399001': '深证成指',
                'sz399006': '创业板指',
                'sh000300': '沪深300',
                'sz399905': '中证500'
            };
            return names[code] || code;
        }

        // 测试Redis连接
        async function testRedis() {
            try {
                showMessage('正在测试Redis连接...', 'info');
                const response = await fetch('/api/market/redis-test');
                const result = await response.json();
                
                if (result.redis_connected) {
                    showMessage('✅ Redis连接正常', 'success');
                } else {
                    showMessage('⚠️ Redis连接失败，使用内存缓存', 'error');
                }
            } catch (error) {
                showMessage('❌ Redis测试失败: ' + error.message, 'error');
            }
        }

        // 显示消息
        function showMessage(message, type) {
            const messageArea = document.getElementById('messageArea');
            const className = type === 'success' ? 'success' : type === 'error' ? 'error' : 'info';
            
            messageArea.innerHTML = `<div class="${className}">${message}</div>`;
            
            setTimeout(() => {
                messageArea.innerHTML = '';
            }, 5000);
        }

        // 开始自动刷新
        function startAutoRefresh() {
            if (updateInterval) return;
            
            updateInterval = setInterval(() => {
                refreshData();
            }, 5000); // 每5秒刷新一次
        }

        // 停止自动刷新
        function stopAutoRefresh() {
            if (updateInterval) {
                clearInterval(updateInterval);
                updateInterval = null;
            }
        }
    </script>
</body>
</html>
